﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Logistics.Utility
{
    /// <summary>
    /// 类型转换工具类
    /// </summary>
    public class Parser
    {
        #region 私有静态变量

        private static DateTime _unixStartTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

        #endregion

        /// <summary>
        /// 字符串转日期
        /// </summary>
        /// <param name="str">输入的日期字符串</param>
        /// <returns>返回转换后的日期</returns>
        public static DateTime? ToDateTime(string str)
        {
            DateTime time;
            if (DateTime.TryParse(str, out time))
            {
                return time;
            }
            return null;
        }

        /// <summary>
        /// 对象转字符串
        /// </summary>
        /// <param name="obj">不限类型的对象</param>
        /// <returns>返回转换后的字符串</returns>
        public static string ToString(object obj)
        {
            var str = "";

            if (obj is DateTime)
            {
                str = ((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss").Replace(" 00:00:00", "");
            }
            else
            {
                str = obj == null ? null : obj.ToString();
            }

            return str;
        }

        /// <summary>
        /// 字符串转整型
        /// </summary>
        /// <param name="obj">输入的字符串</param>
        /// <returns>返回转换后的整型</returns>
        public static int ToInt(object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            int res;
            var str = obj.ToString().Trim();
            return int.TryParse(str, out res) ? res : 0;
        }

        /// <summary>
        /// 字符串转长整型
        /// </summary>
        /// <param name="obj">输入的字符串</param>
        /// <returns>返回转换后的长整型</returns>
        public static long ToLong(object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            long res;
            var str = obj.ToString().Trim();
            return long.TryParse(str, out res) ? res : 0;
        }

        /// <summary>
        /// 对象转bool类型，大于0的整型或者字符串“true”的转换结果为true，其他均为false
        /// </summary>
        /// <param name="obj">输入的字符串</param>
        /// <returns>返回转换后的bool</returns>
        public static bool ToBoolean(object obj)
        {
            bool res;
            if (obj is int)
            {
                res = (int)obj > 0;
            }
            else
            {
                var str = obj.ToString().ToLower();
                res = str.Equals("true");
            }
            return res;
        }

        /// <summary>
        /// 字符串转GUID, 转换失败则返回Guid.Empty.
        /// </summary>
        /// <param name="id">输入的字符串</param>
        /// <returns>返回转换后的Guid, 转换失败则返回Guid.Empty</returns>
        public static Guid ToGuid(string id)
        {
            Guid gid;
            return Guid.TryParse(id.Trim(), out gid) ? gid : Guid.Empty;
        }

        /// <summary>
        /// 将时间戳转为DateTime
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns>返回DateTime</returns>
        public static DateTime StampToDateTime(long timeStamp)
        {
            var str = timeStamp.ToString();
            for (var i = str.Length; i < 17; i++)
            {
                str += "0";
            }
            var stamp = new TimeSpan(long.Parse(str));
            return _unixStartTime.Add(stamp);
        }

        /// <summary>
        /// 将DateTime转为时间戳
        /// </summary>
        /// <param name="dateTime">DateTime</param>
        /// <returns>返回一个16位时间戳</returns>
        public static long DateTimeToStamp(DateTime dateTime)
        {
            var stamp = dateTime - _unixStartTime;
            return (long)stamp.TotalSeconds;
        }

        /// <summary>
        /// 将DataTable转为List
        /// </summary>
        /// <typeparam name="T">泛型，需要转换成类型</typeparam>
        /// <param name="dataTable">需要转换的DataTable类型数据</param>
        /// <returns>返回一个List</returns>
        public static List<T> ToList<T>(DataTable dataTable)
        {
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());

            foreach (DataRow item in dataTable.Rows)
            {
                var props = Activator.CreateInstance<T>();
                for (var i = 0; i < dataTable.Columns.Count; i++)
                {
                    var info = plist.Find(p => p.Name == dataTable.Columns[i].ColumnName);
                    if (info != null && !Convert.IsDBNull(item[i]))
                    {
                        info.SetValue(props, item[i], null);
                    }
                }
                list.Add(props);
            }

            return list;
        }

        /// <summary>
        /// 将List转为DataTable
        /// </summary>
        /// <typeparam name="T">泛型，被转换的类型</typeparam>
        /// <param name="list">需要转换的List类型数据</param>
        /// <returns>返回一个DataTable</returns>
        public static DataTable ToDataTable<T>(List<T> list)
        {
            var result = new DataTable();
            if (list.Count > 0)
            {
                var propertys = typeof(T).GetProperties();
                foreach (var pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                foreach (var t in list)
                {
                    var tempList = new ArrayList();
                    foreach (var pi in propertys)
                    {
                        var obj = pi.GetValue(t, null);
                        if (obj != null && obj != DBNull.Value)
                            tempList.Add(obj);
                    }
                    var array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
    }
}